import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  //    baseURL:'http://49.233.47.187:8080',
  baseURL:'http://59.198.2.188:80/websiteService',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 200000 // request
})
service.interceptors.request.use(
  async config => {
    if (getToken()) {
      config.headers['userToken'] = getToken()
    }
    if (getToken() && store.getters.userInfo) {
      const userInfo = store.getters.userInfo
      // 请求参数控制
      if ('params' in config) {
      } else if ('query' in config) {
        config.headers['Content-Type'] = 'application/json'
        config.data = (config.query)
      } else {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        config.data = qs.stringify(config.data)
      }
    } else {
      // 请求参数控制
      if (!config.params) {
        if (typeof config.data === 'undefined') {
          config.data = {}
        }
        // config.headers['Content-Type'] = 'application/json'
        // if (config.data) {
        //   config.data = qs.stringify(config.data)
        // }
        // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        // if (config.data) {
        //   config.data = qs.stringify(config.data)
        // }

      }
    }
    // 解决ie get缓存问题
    if (config.method == 'get') {
      if (config.params) {
        config.params['accessTime'] = new Date().getTime()
      } else {
        config.url = config.url + `?accessTime=${new Date().getTime()}`
      }
    }
    // config.headers['onceToken'] = await getOnceTokenFn().then(response => {
    //   return response
    // })
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code !== 0) {
      if (res.code === 50008) {
        // 刷新或重新操作
        Message({
          message: res.message || '非法Token值，请您重新操作或刷新页面',
          type: 'error',
          duration: 5 * 1000
        })
        return new Error('非法Token值，请你重新操作或刷新页面')
      } else if (res.code === 50012 || res.code === 50014) {
        // 重新登录
        MessageBox.confirm('您的登录已过期，您可以取消停留在此页面，或重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            // 跳转登录页，无重定向，多端登录在permission中处理
            router.push('/')
          })
        }).catch(async() => {

        })
      }else if( res.code == -1){
        return res
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return new Error('Error')
  }
)

export default service
